<template>
	<div ref="el" class="flex-1 flex flex-col">
		<feeds-toolbar v-model:order="order" @update:order="onOrderChange"></feeds-toolbar>
		<base-list-plus
			auto
			class="flex-1"
			:loading="loading"
			:isFinish="isFinish"
			:isEmpty="isEmpty"
			:error="error"
			@load="search"
			@reload="search(true)">
			<base-waterfall :data="list" :column="lgCols" :rowSpacing="15" :picturePreReading="false">
				<template v-slot="{ item, width }">
					<up-feed-item :data="item" :style="{ width }" />
				</template>
			</base-waterfall>
		</base-list-plus>
	</div>
</template>

<script lang="ts" setup>
import FeedsToolbar from './feeds-toolbar.vue'
import { BaseWaterfall, BaseListPlus } from '@/components/base'
import { UpFeedItem } from '@/components/up'
import { ref, watch } from 'vue'
import { getFeedsListFilter } from '@/api/feed'
import { useListCols, useRequest } from '@/hooks'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore, useFeedStore } from '@/store'
import { FeedType } from '@/types'

const appStore = useAppStore()
const feedStore = useFeedStore()

const route = useRoute()
const router = useRouter()

const el = ref(null)

const { lgCols } = useListCols(el)

const order = ref<any>('created_at')

const { run, loading, error, isFinish, isEmpty, list } = useRequest<FeedType>(getFeedsListFilter, {
	pageSize: 12,
	onSuccess: () => {
		feedStore.setList(list.value)
	}
})

const onOrderChange = (val: string) => {
	if (val !== 'created_at') {
		router.push('/feed?type=' + val)
	} else {
		router.push('/feed')
	}
}

watch(
	() => route.query.type,
	(val) => {
		order.value = val || 'created_at'
	},
	{
		immediate: true
	}
)

const search = (refresh = false) => {
	run(
		{
			regionCode: appStore.region,
			oddsStyle: appStore.odds,
			locale: appStore.lang,
			currency: appStore.currency,
			orderBy: order.value,
			hideLive: false,
			convMarket: true,
			usefilterdefault: true
		},
		{ refresh }
	)
}

watch(
	() => [appStore.region, appStore.odds, appStore.lang, appStore.currency, order.value],
	() => {
		search(true)
	},
	{ immediate: true }
)
</script>
